import { ref, reactive, computed } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { getAddressListAPI, setDefaultAddressAPI } from '@/api/adress'
import { useAuthStore } from '@/stores/auth'

export const useAddressStore = defineStore(
  'address',
  () => {
    const { getUserInfo } = useAuthStore()
    const { userInfo } = storeToRefs(useAuthStore())

    // 控制地址Modal显示
    const isAdressModalShow = ref(false)

    // 设置用户默认地址
    const setDefaultAddress = async (id: string) => {
      await setDefaultAddressAPI({ id })
      await getUserInfo()
      console.log(userInfo.value)
    }

    // 用户默认地址
    const defaultAddress = computed(() => {
      const a = addressList.value.find((item: any) => item.id == userInfo.value.address)
      if (!a) {
        return addressList.value[0]
      }
      return a
    })
    const statusName = ref('新增')
    // 收货地址
    const addressList = ref<any>([])

    // 获取用户收货地址
    const getAddressList = async () => {
      addressList.value = await getAddressListAPI()
      console.log(addressList.value)
    }
    getAddressList()

    // 表单
    type AddressForm = {
      province: string
      city: string
      district: string
      address: string
      phone: string
      username: string
      area: any[]
    }

    const addressForm = ref<AddressForm>({
      province: '',
      city: '',
      district: '',
      address: '',
      phone: '',
      username: '',
      area: []
    })

    return {
      getAddressList,
      addressList,
      isAdressModalShow,
      setDefaultAddress,
      defaultAddress,
      addressForm,
      statusName
    }
  },
  {
    persist: true
  }
)
